package api

import (
	"errors"
	"fmt"
	"io"
	"log"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"os"
	"path"
	"strings"
	"time"

	"github.com/labstack/echo/v4"
)

// @Summary 上傳圖片
// @Description 上傳圖片
// @Accept  json
// @Produce  json
// @Tags Public
// @Router /api/uploader [POST]
func (base *Controller) Uploader(c echo.Context) error {
	log.Println("c:", c)
	form, err := c.MultipartForm()
	log.Println("form:", form)
	log.Println("err:", err)
	if err != nil {
		return util.BadParam(c, err)
	}

	domain := global.Config.GetString("uploader.domain")
	defineSavePath := "../../../uploads/"
	_, err = os.Stat(defineSavePath)
	if err != nil {
		os.Mkdir(defineSavePath, os.ModePerm)
	}

	//按日期存储
	date := time.Now().Format("2006-01-02") + "/"

	_, err = os.Stat(defineSavePath + date)
	if err != nil {
		os.Mkdir(defineSavePath+date, os.ModePerm)
	}

	fs := form.File["file"]
	var previews []string
	for i, file := range fs {
		if i >= 9 {
			break
		}
		switch file.Header.Get("Content-Type") {
		case "image/gif", "image/png", "image/jpeg", "image/bmp", "image/webp", "image/jpg":
		default:
			return util.BuildFail(c, 1, "", errors.New("不支持的图片格式"))
		}
		src, err := file.Open()
		if err != nil {
			return util.BuildFail(c, 1, "文件服务器保存失败1", err)
		}
		defer src.Close()
		// Destination
		fileRename := fmt.Sprintf("%d%s", time.Now().UnixNano(), path.Ext(file.Filename))
		dst, err := os.Create(defineSavePath + date + fileRename)
		if err != nil {
			return util.BuildFail(c, 1, "文件服务器保存失败2", err)
		}
		defer dst.Close()

		// Copy
		if _, err = io.Copy(dst, src); err != nil {
			return util.BuildFail(c, 1, "服务器保存失败3", err)
		}

		previews = append(previews, domain+date+fileRename)
	}
	return util.BuildSuccess(c, strings.Join(previews, ","), "")
}
